# -*- coding:utf8 -*- #
# ProjectName: smalleel-api-tools
# FileName: merchant_acceptance.py
# @DateTime :2023/3/2 17:27
# @Author :
# @Description:小程序添加电表和基站
from common.util.jsonUtil.jsonUtil import read_sql_json, read_extract_json
from common.util.mySqlUtil.mySqlUtil import select_sql
from common.util.randomUtil.randomUtil import get_random_name
from common.util.requestUtil.requestUtil import RequestsUtil
from tool.process.config.smalleelApi import MerchantApi
from tool.process.config.acceptConfig import AcceptanceConfig


class Merchant:
    def __init__(self):
        self.config = AcceptanceConfig()
        self.api = MerchantApi()
        self.req = RequestsUtil()
        self.proId = self.config.proId
        self.collectorName = self.config.collectorName
        self.Authorization = self.plaform_token = read_extract_json('tokenMerchant', 2)
        self.headers = {"Authorization": self.Authorization}

    def switchpro(self):
        """
        aid: proid
        type: 区分层级（集团区域项目）
        """
        url = self.api.switchMerchantPro
        params = {"aid": self.proId, "type": 5}
        response = self.req.send_request("post", url=url, params=params, headers=self.headers, parameterFormat="data")
        if response["code"] == 200:
            print(f"已切换到: {self.config.proName}")
        else:
            print("项目切换失败！")

    def add_Collector(self, collectNo, num):
        """
            no:基站号
            num:添加数量
        """
        self.switchpro()

        for i in range(num):
            if num >= 1:
                if isinstance(collectNo, str):
                    if isinstance(collectNo[0], str):
                        if i == 0:
                            collectNo = collectNo
                        else:
                            collectEnd = int(collectNo[1::]) + 1
                            collectNo = f"{collectNo[0]}{collectEnd}"
            else:
                print("数量错误")
            if self.config.deviceType == 1:
                url = self.api.addCollector
                modelCode = str(select_sql(read_sql_json('acceptance_sql', 'modelCode', 1, self.collectorName))[0][0])
                params = {"collectorDeviceNo": collectNo, "typeName": self.collectorName + modelCode,
                          "collectorName": get_random_name(description='基站')}
                response = self.req.send_request("post", url=url, params=params, headers=self.headers)
                if response["code"] == 200:
                    print(f"电表基站{collectNo}--{response['msg']}")
                else:
                    print(response)
            elif self.config.deviceType == 6:
                url = self.api.addWaterCollector
                params = {"aid": self.config.collectionModelId,
                          "baseDeviceName": '水' + str(collectNo),
                          "baseDeviceNo": collectNo}
                response = self.req.send_request("post", url=url, params=params, headers=self.headers)
                if response["code"] == 200:
                    print(f"水表基站{collectNo}--{response['msg']}")
                else:
                    print(response)

    def add_Db(self, dbNo, num):
        """
            新增电表
            no:表号
            num:添加数量
        """
        tagId = select_sql(read_sql_json('acceptance_sql', 'tagId', 1, self.proId))[0][0]
        collectorId = select_sql(read_sql_json('acceptance_sql', 'collectorId', 1, self.proId))[0][0]
        self.switchpro()
        url = self.api.addDb
        try:
            for i in range(num):
                params = {"tagid": tagId,
                          "no": dbNo,
                          "name": get_random_name(description='商户'),
                          "bjlx": 1,
                          "bei": 1, "credit": 500, "warnline": 500, "feetype": 1, "priceType": 1,
                          "priceContent": "0.635",
                          "plusPrice": 0.5, "balance": 0, "modelName": "JM-D-610G", "useCollector": True,
                          "authControl": True,
                          "installBefore": {}, "bjStatus": 0, "plusPriceName": "公损费",
                          "collectorId": collectorId}
                response = self.req.send_request("post", url=url, params=params, headers=self.headers)
                if response["code"] == 200:
                    print(f"电表{dbNo}--{response['msg']}")
                else:
                    print(response)
                dbNo = int(dbNo) + 1
        except Exception as e:
            print("数量错误")

    def replace_Db(self, newNo, oldNo, bei=1, isBuy=0):
        """
        替换电表，默认新表的倍率为1且是非采买替换
        """
        self.switchpro()
        url = self.api.replaceDb
        params = {
            "newno": int(newNo),
            "oldno": int(oldNo),
            "bei": bei,
            "isBuy": isBuy
        }
        response = self.req.send_request("post", url=url, params=params, headers=self.headers)
        print(response)

    def add_WaterDb(self, waterNo, num):
        """
        新增水表
        waterNo：水表表号
        num：水表数
        """
        self.switchpro()
        url = self.api.addWaterDb
        tagId = select_sql(read_sql_json('water_sql', 'waterTag', 1, self.proId))[0][0]
        deviceTypeName = select_sql(read_sql_json('water_sql', 'waterModule', 1, self.config.waterModelId))[0][0]
        for i in range(num):
            params = {"balance": 10,
                      "credit": 50,
                      "deviceTypeName": deviceTypeName,
                      "gateOpen": 1,
                      "meterType": 1,
                      "modelId": self.config.waterModelId,
                      "payType": 1,
                      "plusPrice": "12",
                      "priceContent": "11",
                      "priceType": 1,
                      "tagId": tagId,
                      "unitPrice": "1",
                      "warnLimit": "14",
                      "waterName": get_random_name(description='水表'),
                      "waterNo": waterNo
                      }
            response = self.req.send_request("post", url=url, params=params, headers=self.headers)
            if response["code"] == 200:
                print(f"水表{waterNo}--{response['msg']}")
            else:
                print(response)
            waterNo = int(waterNo) + 1


if __name__ == '__main__':
    me = Merchant()
    me.switchpro()
    # me.replace_Db(455202313184, 455202329254)
    me.add_Collector("C54666506277", 1)
